package com.lenovo.smarttraffic.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.MapPakerBean;
import com.lenovo.smarttraffic.bean.RouteInfoBean;

import com.lenovo.smarttraffic.util.VolleyUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Caleb.F
 * on 2019-11-20
 * at 21:56
 */
public class MapLineActivity extends BaseActivity {
    private MapView mMapLine;
    private Spinner mSpinner3;
    private Spinner mSpinner2;
    private TextView mTvDetails;
    private TextView mTvsearch;
    private MapPakerBean parkInfo;
    private AMap amap;
    private ProgressDialog mProgressDialog;
    private Map<String, LatLng> linkedMap;
    private List<String> mspotList;
    private String startSpot;
    private String endSpot;
    private List<RouteInfoBean.RouteBean.PathsBean.StepsBean> steps;
    private RouteInfoBean routeInfoBean;


    private static final String TAG = "MapLineActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        linkedMap = new LinkedHashMap<>();
        linkedMap.put("联想大厦", new LatLng(40.042737, 116.309884));
        linkedMap.put("西铁营桥", new LatLng(39.860512, 116.347593));
        linkedMap.put("G107", new LatLng(39.802303, 116.209749));
        linkedMap.put("G2路段", new LatLng(39.847603, 116.472871));
        linkedMap.put("联想总部园区", new LatLng(40.046307, 116.273117));
        linkedMap.put("首都机场", new LatLng(40.080525, 116.603039));
        linkedMap.put("北京西站", new LatLng(39.89491, 116.322056));
        linkedMap.put("北京南站", new LatLng(39.865195, 116.378545));
        linkedMap.put("天安门", new LatLng(39.908696, 116.397474));
        linkedMap.put("联想研究院", new LatLng(40.048084, 116.272628));
        mspotList = new ArrayList<>();
        mProgressDialog = new ProgressDialog(this);
        initView();
        parkInfo = ParkDetailActivity.getParkInfo(getIntent());
        mMapLine.onCreate(savedInstanceState);
        if (amap == null) {
            amap = mMapLine.getMap();
        }
        initMarker();
    }

    private void getData() {
        amap.clear();
        String startSpot = (String) mSpinner2.getSelectedItem();
        String endSpot = (String) mSpinner3.getSelectedItem();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("origin", startSpot);
            jsonObject.put("destination", endSpot);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mProgressDialog.show();
        VolleyUtil.post("GetRouteInfo.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                routeInfoBean = new Gson().fromJson(jsonObject.toString(), RouteInfoBean.class);
                if (routeInfoBean.getRESULT().equals("S")) {
                    mProgressDialog.cancel();
                    routeInfoBean.setStartSpot(mSpinner2.getSelectedItem().toString());
                    routeInfoBean.setEndSpot(mSpinner3.getSelectedItem().toString());
                    List<RouteInfoBean.RouteBean.PathsBean> paths = routeInfoBean.getRoute().getPaths();
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                    for (RouteInfoBean.RouteBean.PathsBean item :
                            paths) {
                        steps = item.getSteps();
                        Message message1 = new Message();
                        message1.what = 2;
                        handler.sendMessage(message1);
                    }
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }


    Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case 1:
                addMarker();
                break;
            case 2:
                drawLine();
                break;
            default:
                break;
        }
        return false;
    });

    private void addMarker() {
        String origin = routeInfoBean.getRoute().getOrigin();
        String destination = routeInfoBean.getRoute().getDestination();
        LatLng startLatLng = (new LatLng(Double.parseDouble(origin.split(",")[1]),
                Double.parseDouble(origin.split(",")[0])));
        LatLng endLatLng = (new LatLng(Double.parseDouble(destination.split(",")[1]),
                Double.parseDouble(destination.split(",")[0])));

        amap.addMarker(new MarkerOptions().position(startLatLng).
                icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.start))));
        amap.addMarker(new MarkerOptions().position(endLatLng).
                icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.end))));

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        LatLngBounds build = builder.include(startLatLng).include(endLatLng).build();
        amap.moveCamera(CameraUpdateFactory.newLatLngBounds(build, 1));

    }

    private void drawLine() {
        List<LatLng> latlngs = new ArrayList<>();
        for (RouteInfoBean.RouteBean.PathsBean.StepsBean item :
                steps) {
            List<String> list = Arrays.asList(item.getPolyline().split(";"));
            for (String item1 :
                    list) {
                latlngs.add(new LatLng(Double.parseDouble(item1.split(",")[1]), Double.parseDouble(item1.split(",")[0])));
            }

        }
        amap.addPolyline(new PolylineOptions().addAll(latlngs).color(Color.RED).width(20f));
    }

    private void initMarker() {
        Toast.makeText(MapLineActivity.this, "已为您定位到" + parkInfo.getParkerName(), Toast.LENGTH_SHORT).show();
        LatLng latLng = new LatLng(Double.parseDouble(parkInfo.getCoordinate().split(",")[1]),
                Double.parseDouble(parkInfo.getCoordinate().split(",")[0]));
        amap.moveCamera(CameraUpdateFactory.zoomTo(14));
        amap.addMarker(new MarkerOptions().position(latLng).title(parkInfo.getParkerName())
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.marker_self))));
        amap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapLine.onResume();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_map_line;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapLine.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapLine.onSaveInstanceState(outState);
    }

    private void initView() {
        initToolBar("离线地图");
        mMapLine = findViewById(R.id.map_line);
        mSpinner3 = findViewById(R.id.spinner3);
        mSpinner2 = findViewById(R.id.spinner2);
        mTvDetails = findViewById(R.id.tv_details);
        mTvsearch = findViewById(R.id.tv_line_search);
        mspotList.addAll(linkedMap.keySet());
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, mspotList);
        mSpinner2.setAdapter(stringArrayAdapter);
        mSpinner2.setSelection(0);
        mSpinner3.setAdapter(stringArrayAdapter);
        mSpinner3.setSelection(1);
        mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                startSpot = mspotList.get(position);
                checkforRepeat();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mSpinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                endSpot = mspotList.get(position);
                checkforRepeat();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mTvsearch.setOnClickListener(v -> {
            getData();
        });
        mTvDetails.setOnClickListener(v -> {
            if (routeInfoBean == null) {
                Toast.makeText(this, "请查询路线后查看路线详情", Toast.LENGTH_SHORT).show();
                return;
            } else {
                EventBus.getDefault().postSticky(routeInfoBean);
                startActivity(new Intent(MapLineActivity.this, MapDetailActivity.class));
            }
        });

    }

    private void checkforRepeat() {
        if (startSpot == null) {
            return;
        } else {
            if (startSpot.equals(endSpot)) {
                mSpinner2.setSelection(0);
                mSpinner3.setSelection(1);
                Toast.makeText(this, "不可选择同一地点", Toast.LENGTH_SHORT).show();
            }
        }
    }


}
